/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;

/**
 * Input Errors Interceptor, this interceptor will call a prepareInputErrors if the return type of the action is
 * input.  This interceptor should be placed before the validation interceptor, in the interceptor stack.
 * @author Adam
 * @version $Id: InputErrorsInterceptor.java 16 2009-04-12 05:05:02Z a.ruggles $
 * 
 * Created on Nov 29, 2008 at 9:32:43 AM 
 */
public class InputErrorsInterceptor extends AbstractInterceptor {
	/**
	 * Serial Version UID.
	 */
	private static final long serialVersionUID = -6078296278760537688L;

	/**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private static final Logger LOG = LoggerFactory.getLogger(InputErrorsInterceptor.class);

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
    public String intercept(final ActionInvocation invocation) throws Exception {
    	invocation.addPreResultListener(new PreResultListener() {
    		/**
    		 * {@inheritDoc}
    		 * @see com.opensymphony.xwork2.interceptor.PreResultListener#beforeResult(
    		 * com.opensymphony.xwork2.ActionInvocation, java.lang.String)
    		 */
    		public void beforeResult(final ActionInvocation invocation, final String resultCode) {
    			LOG.debug("Result Code Returned [{}]", resultCode);
    			if (Action.INPUT.equals(resultCode)) {
    				final Action action = (Action) invocation.getAction();
    				if (action instanceof InputErrorsAware) {
    					LOG.debug("Calling Prepare Input Errors");
    					((InputErrorsAware) action).prepareInputErrors();
    				}
    			}
    		}
    	});
    	return invocation.invoke();
    }
}
